package com.myapp.ruyixing.ui;

import static android.view.View.GONE;

import java.util.Calendar;

import android.app.AlertDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.myapp.ruyixing.Config;
import com.myapp.ruyixing.R;
import com.myapp.ruyixing.http.RYHttpClient;
import com.myapp.ruyixing.http.RYHttpResponseHandler;
import com.myapp.ruyixing.model.Reservation;
import com.myapp.ruyixing.model.Reserve;
import com.myapp.ruyixing.ui.widget.DatePickerFragment;
import com.myapp.ruyixing.ui.widget.TimePickerFragment;
import com.myapp.ruyixing.ui.widget.TitleBar;
import com.myapp.ruyixing.utils.LoginHelper;
import com.myapp.ruyixing.utils.TimeUtils;

public class ReservationActivity extends FragmentActivity implements
		OnDateSetListener, OnTimeSetListener {

	Reserve mReserve;
	int mType = 0;

	RYHttpResponseHandler mHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				Reservation reservation = (Reservation) o;
				onLoadingDataFinished(true, reservation);
			} catch (Exception e) {
				onLoadingDataFinished(false, null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onLoadingDataFinished(false, null);
		}
	};

	RYHttpResponseHandler mGetReserveHttpResponseHandler = new RYHttpResponseHandler() {

		@Override
		public void onSuccess(Object o) {
			try {
				Reserve reserve = (Reserve) o;
				onGetReserveFinished(true, reserve);
			} catch (Exception e) {
				onGetReserveFinished(false, null);
			}
		}

		@Override
		public void onFailure(Throwable throwable) {
			onGetReserveFinished(false, null);
		}
	};

	private void onGetReserveStarted(String bduss, String shopid) {
		showLoading(true, "加载中");
		RYHttpClient.getReserve(this, mGetReserveHttpResponseHandler, bduss,
				shopid);
	}

	private void onGetReserveFinished(boolean succeed, Reserve reserve) {
		showLoading(false, "加载中");
		if (succeed && reserve != null && reserve.errno == 0) {
			mReserve = reserve;
			findViewById(R.id.layout_content).setVisibility(View.VISIBLE);
			if (TextUtils.isEmpty(reserve.orderserve)) {
				findViewById(R.id.text_xiangshou).setVisibility(View.GONE);
				findViewById(R.id.text_discount).setVisibility(View.GONE);
			} else {
				((TextView) findViewById(R.id.text_discount))
						.setText(reserve.orderserve);
			}
			if (TextUtils.isEmpty(reserve.shopname)) {
				findViewById(R.id.text_shangjiamingcheng).setVisibility(
						View.GONE);
				findViewById(R.id.text_shopname).setVisibility(View.GONE);
			} else {
				((TextView) findViewById(R.id.text_shopname))
						.setText(reserve.shopname);
			}
			if (reserve.items != null && reserve.items.size() > 0
					&& !TextUtils.isEmpty(reserve.items.get(0))) {
				((TextView) findViewById(R.id.text_type)).setText(reserve.items
						.get(0));
			}
		} else {
			findViewById(R.id.layout_content).setVisibility(View.GONE);
			showToast("加载失败");
		}
	}

	private void onLoadingDataStarted(String bduss, String shopid, String name,
			int sex, String phone, String date, String time, String num,
			String type, String content) {
		showLoading(true, "加载中");
		RYHttpClient.doReserve(this, mHttpResponseHandler, bduss, shopid, name,
				sex, phone, date, time, num, type, content);
	}

	private void onLoadingDataFinished(boolean succeed, Reservation reservation) {
		if (succeed && reservation != null && reservation.errno == 0) {
			showToast("成功提交订单！");
			finish();
		} else {
			showLoading(false, "加载中");
			if (reservation != null && !TextUtils.isEmpty(reservation.msg)) {
				showToast(reservation.msg);
			} else {
				showToast("订单提交失败！");
			}
		}
	}

	public static void startReservationActivity(Context context, String shopid) {
		if (context == null || TextUtils.isEmpty(shopid)) {
			return;
		}
		Intent intent = new Intent(context, ReservationActivity.class);
		intent.putExtra("shopid", shopid);
		context.startActivity(intent);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_reservation);
		((TitleBar) findViewById(R.id.title_bar))
				.setOnIconClickedListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						onBackPressed();
					}
				});

		((TextView) findViewById(R.id.text_date)).setText(TimeUtils
				.getEEDayString(Calendar.getInstance()));

		((TextView) findViewById(R.id.text_time)).setText(TimeUtils
				.getTimeString(Calendar.getInstance()));

		findViewById(R.id.text_gender).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						String text = ((TextView) findViewById(R.id.text_gender))
								.getText().toString();
						if ("女士".equals(text)) {
							((TextView) findViewById(R.id.text_gender))
									.setText("先生");
						} else {
							((TextView) findViewById(R.id.text_gender))
									.setText("女士");
						}
					}
				});

		findViewById(R.id.text_date).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Calendar c = TimeUtils
						.parsrEEDate(((TextView) findViewById(R.id.text_date))
								.getText().toString());
				pickDate(c);
			}
		});

		findViewById(R.id.text_time).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Calendar c = TimeUtils
						.parsrTime(((TextView) findViewById(R.id.text_time))
								.getText().toString());
				pickTime(c);
			}
		});

		findViewById(R.id.text_type).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mReserve == null || mReserve.items == null
						|| mReserve.items.size() == 0) {
					return;
				}
				String[] array = new String[mReserve.items.size()];
				for (int i = 0; i < array.length; i++) {
					array[i] = mReserve.items.get(i);
				}
				AlertDialog.Builder builder = new AlertDialog.Builder(
						ReservationActivity.this);
				builder.setTitle("请选择").setItems(array,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								String s = mReserve.items.get(which);
								mType = which;
								((TextView) findViewById(R.id.text_type))
										.setText(s);
							}
						});
				builder.create().show();
			}
		});

		findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				String bduss = LoginHelper.getInstance().getBDUSS();
				if (TextUtils.isEmpty(bduss)) {
					showToast("登录失效，请重新登录！");
					finish();
					return;
				}
				String shopid = getIntent().getStringExtra("shopid");
				if (TextUtils.isEmpty(shopid)) {
					showToast("无效商家");
					finish();
					return;
				}
				String name = ((EditText) findViewById(R.id.edit_name))
						.getText().toString();
				if (TextUtils.isEmpty(name)) {
					showToast("请输入您的姓名！");
					findViewById(R.id.edit_name).requestFocus();
					return;
				}
				String phone = ((EditText) findViewById(R.id.edit_phone))
						.getText().toString();
				if (TextUtils.isEmpty(phone)) {
					showToast("请输入您的电话！");
					findViewById(R.id.edit_phone).requestFocus();
					return;
				}

				String num = ((EditText) findViewById(R.id.edit_number))
						.getText().toString();
				if (TextUtils.isEmpty(num)) {
					showToast("请输入就餐人数！");
					findViewById(R.id.edit_number).requestFocus();
					return;
				}

				String date = ((TextView) findViewById(R.id.text_date))
						.getText().toString();

				String time = ((TextView) findViewById(R.id.text_time))
						.getText().toString();

				String content = ((EditText) findViewById(R.id.edit_msg))
						.getText().toString();

				if (Config
						.isShopManagerVersionAndNotBinded(ReservationActivity.this)) {
					showToast("您未绑定会员账号，请绑定后再使用此功能");
				} else {
					String sexs = ((TextView) findViewById(R.id.text_gender))
							.getText().toString();
					String type = ((TextView) findViewById(R.id.text_type))
							.getText().toString();
					int sex = sexs.equals("女士") ? 2 : 1;
					onLoadingDataStarted(bduss, shopid, name + sexs, sex,
							phone, date, time, num, type, content);
				}
			}
		});
		String shopid = getIntent().getStringExtra("shopid");
		onGetReserveStarted(LoginHelper.getInstance().getBDUSS(), shopid);
	}

	private void pickDate(Calendar c) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag(
				"datepicker");
		if (prev != null) {
			return;
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		DialogFragment newFragment = DatePickerFragment
				.getDatePickerFragment(c);

		newFragment.show(ft, "datepicker");
	}

	private void pickTime(Calendar c) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		Fragment prev = getSupportFragmentManager().findFragmentByTag(
				"timepicker");
		if (prev != null) {
			return;
		}
		ft.addToBackStack(null);

		// Create and show the dialog.
		DialogFragment newFragment = TimePickerFragment
				.getTimePickerFragment(c);

		newFragment.show(ft, "timepicker");
	}

	private void showToast(String msg) {
		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
	}

	private void showLoading(boolean show, String msg) {
		if (isFinishing()) {
			return;
		}
		if (show) {
			findViewById(R.id.layout_loading).setVisibility(View.VISIBLE);
			((TextView) findViewById(R.id.text_loading)).setText(msg);
		} else {
			findViewById(R.id.layout_loading).setVisibility(GONE);
		}
	}

	@Override
	public void onDateSet(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		CharSequence dateString = TimeUtils.getEEDayString(TimeUtils
				.getCalendar(year, monthOfYear, dayOfMonth));
		((TextView) findViewById(R.id.text_date)).setText(dateString);
	}

	@Override
	public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
		CharSequence timeString = TimeUtils.getTimeString(TimeUtils
				.getCalendar(hourOfDay, minute));
		((TextView) findViewById(R.id.text_time)).setText(timeString);
	}

}
